<?php

declare(strict_types=1);

namespace app\common\model;

use addons\WeChat\facade\WeChat;

class MakeOrder extends Base
{

    protected $name = 'make_order';
    protected $type = [
        'make_time' => 'timestamp',
    ];

    public function user()
    {
        return $this->hasOne(User::class, 'id', 'uid')->field('id,code,nickname,photo,mobile');
    }
    public function getStatusAttr($value)
    {
        return self::getOrderStatus($value);
    }

    public static function getOrderStatus($value, $type = 1)
    {
        $status = [1 => '待服务', 2 => '进行中', 3 => '已完成', 7 => '已取消'];
        return $type == 1 ? $status[$value] : $status;
    }

    public function getTypeAttr($value)
    {
        return self::getType($value);
    }
    public static function getType($value, $type = 1)
    {
        $status = [1 => '车辆预约', 2 => '医护上门', 3 => '护理员上门'];
        return $type == 1 ? $status[$value] : $status;
    }
    public  static function getCarType($value, $type = 1)
    {
        $status = [1 => '普通转运型', 2 => '医疗转运车', 3 => '监护转运型'];
        return $type == 1 ? $status[$value] : $status;
    }
    public static function submitOrder($params, $user)
    {
        parent::startTrans();
        try {
            $product = Make::where('id', $params['make_id'])->find();
            if (empty($product)) {
                return ['code' => -1, 'msg' => '服务项目不存在'];
            }
            if ($product['type'] == 1 && empty($params['car_type'])) {
                return ['code' => -1, 'msg' => '选择车型'];
            }
            $new = parent::create([
                'sn' => date('YmdHis') . $user->id . rand(100000, 999999),
                'uid' => $user->id,
                'money' => $product->money,
                'title' => $product->title,
                'sub_title' => $product->sub_title,
                'type' => $product['type'],
                'icon' => $product->images ? explode(',', $product->images)[0] : '',
                'make_time' => $params['make_time'],
                'make_id' => $params['make_id'],
                'name' => $params['name'],
                'phone' => $params['phone'],
                'num' => $params['num'],
                'start_address' => $params['start_address'] ?? '',
                'end_address' => $params['end_address'],
                'my_address' => $params['my_address'],
                'lat' => $params['lat'],
                'lng' => $params['lng'],
                'note' => $params['note'] ?? '',
                'car_type' => $params['car_type'] ?? 0,
                'case_img' => $params['case_img'] ?? '',
            ]);
            $openidlist = User::where('is_message', 1)->where('wx_openid', '<>', '')->column('wx_openid');
            $address = $params['my_address'];
            if (mb_strlen($address) > 20) {
                $address = mb_substr($address, 0, 20, 'UTF-8');
            }
            $wedatas = [
                'thing3' => [
                    'value' => $params['name'],
                ],
                'phone_number4' => [
                    'value' => $params['phone'],
                ],
                'thing9' => [
                    'value' => !empty($params['note']) ? $params['note'] : $product->title,
                ],
                'time16' => [
                    'value' => date('Y-m-d H:i:s', intval($params['make_time'])),
                ],
                'thing24' => [
                    'value' => $address,
                ]
            ];
            if (!empty($openidlist)) {
                foreach ($openidlist as $v) {
                    self::sendTemplate($v, '3DHEs0r59kSbD1Eo4wvKuOTMZ5IEeItXPjR802pZpcY', $wedatas, '');
                }
            }
            parent::commit();
            return ['code' => 1, 'msg' => '预约成功', 'data' => $new->id];
        } catch (\Exception $e) {
            parent::rollback();
            return ['code' => -1, 'msg' => $e->getMessage()];
        }
    }
    /**
     * 预约订单操作
     */
    public static function editOrder($params, $user)
    {
        parent::startTrans();
        try {
            $info = parent::where('id', $params['id'])->find();
            if (empty($info)) {
                return ['code' => -1, 'msg' => '订单不存在'];
            }
            $type = $params['type'];
            switch ($type) {
                case  'cancel':
                    if ($info->getData('status') != 1) {
                        return ['code' => -1, 'msg' => '无法取消'];
                    }
                    $info->status = 7;
                    $info->cancel_time = time();
                    $info->save();
                    parent::commit();
                    return ['code' => 1, 'msg' => '服务已取消'];
                    break;
                case  'end':
                    if ($info->getData('status') != 2) {
                        return ['code' => -1, 'msg' => '订单无法结束完成'];
                    }
                    $info->status = 3;
                    $info->finish_time = time();
                    $info->save();
                    parent::commit();
                    return ['code' => 1, 'msg' => '订单已完成'];
                    break;
                default:
                    return ['code' => -1, 'msg' => '操作类型错误'];
                    break;
            }
        } catch (\Exception $e) {
            parent::rollback();
            return ['code' => -1, 'msg' => $e->getMessage()];
        }
    }
    /**
     * 订单自动进行
     */
    public static function autoUnderway(): array
    {
        try {
            $time = time();
            //->where('post_time', '<', $time)
            self::where(['status' => 1])->where('make_time', '>', 0)->select()->each(function ($item) {
                $item->status = 2;
                $item->save();
            });
            return ['code' => 1, 'msg' => '服务开始成功'];
        } catch (\Exception $e) {
            return ['code' => -1, 'msg' => $e->getMessage()];
        }
    }
    /**
     * 模板消息发送
     */
    public static function sendTemplate($openid, $template_id, $data, $url = '')
    {
        $userinfo = WeChat::getUserInfoList($openid, 'zh_CN');
        if ($userinfo['subscribe'] == 1) {
            $data = [
                'touser' => $openid,
                'template_id' => $template_id,
                'url' => $url,
                'data' => $data,
            ];
            $res = WeChat::wechatTemplateSend($data);
            return $res;
        } else {
            return 0;
        }
    }
}
